package watermark;

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.documents.WatermarkLayout;
import com.spire.doc.fields.DocPicture;

import java.awt.*;
import java.util.Iterator;

public class MyImageWatermark {
    public static void main(String[] args) {
        String inputFile = "D:\\ChromeDownloads\\20180205170713490.doc";
        String destFile = "D:\\ChromeDownloads\\20180205170713490-1.doc";
        String destFile2 = "C:\\Users\\wmz\\Desktop\\20220211164232510_2.docx";
        String text = "理财有风险，投资需谨慎";
        String imageFile = "D:\\develop\\2024092622174316527.png";



        //textWatermark(inputFile, destFile, text);
        imageWatermark(inputFile, destFile, imageFile);
        //textWatermark(destFile, destFile, text);
    }

    public static void textWatermark(String inputFile, String outputFile,String text){
        Document doc = new Document();

        doc.loadFromFile(inputFile);

        //定义水印图片的纵向坐标位置

        Iterator iterator = doc.getSections().iterator();
        while (iterator.hasNext()) {
            Section section = (Section) iterator.next();
            float y = (float) (section.getPageSetup().getPageSize().getHeight()/2);
            TextWatermark txtWatermark = new TextWatermark();
            txtWatermark.setText(text);
            txtWatermark.setFontSize(40);
            txtWatermark.setColor(Color.GRAY);
            txtWatermark.setLayout(WatermarkLayout.Diagonal);
            section.getDocument().setWatermark(txtWatermark);
        }
        FileFormat docx2013 = FileFormat.Docx_2013;


        FileFormat fileFormat= inputFile.toLowerCase().endsWith("doc")?FileFormat.Doc: FileFormat.Docx;

        //保存文档
        doc.saveToFile(outputFile,fileFormat);
        doc.dispose();
        doc.close();
    }

    public static void imageWatermark(String inputFile, String outputFile,String image){
        Document doc = new Document();
        doc.loadFromFile(inputFile);
       //WatermarkBase watermark = doc.getWatermark();

        //定义水印图片的纵向坐标位置

        Iterator iterator = doc.getSections().iterator();
        while (iterator.hasNext()) {
            Section section = (Section) iterator.next();

            float y = (float) (section.getPageSetup().getPageSize().getHeight()/2);

            PictureWatermark pictureWatermark = new PictureWatermark();
            pictureWatermark.setPicture(image);
            pictureWatermark.setScaling(200);
            section.getDocument().setWatermark(pictureWatermark);

        }

        FileFormat fileFormat= inputFile.toLowerCase().endsWith("doc")?FileFormat.Doc: FileFormat.Docx;
        //保存文档
        doc.saveToFile(outputFile,fileFormat);
        doc.dispose();
        doc.close();
    }
}